#include "cpurankmvcmainwindow.h"
#include "ui_cpurankmvcmainwindow.h"

#include <QSortFilterProxyModel>
#include <httpclient.h>

#include <src/ui/widgets/cpurankitemdelegate.h>
#include <src/ui/widgets/cpurankviewmodel.h>

CpuRankMVCMainWindow::CpuRankMVCMainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::CpuRankMVCMainWindow)
{
    ui->setupUi(this);

    CpuRankViewModel *cpu_rank_model = new CpuRankViewModel;
    CpuRankItemDelegate *cpu_rank_delegate = new CpuRankItemDelegate;
    ui->cpu_rank_list->setModel(cpu_rank_model);
    ui->cpu_rank_list->setItemDelegate(cpu_rank_delegate);

    Response resp = HttpClient::instance().get("https://cpu.bmcx.com/web_system/bmcx_com_www/system/file/cpu/get_data/?lx=cpu&s=1&e=999999");
    if (resp.ok()) {
        for (const auto &var : resp.toList()) {
            cpu_rank_model->append(new CpuRankInfo(var.toMap()));
        }
    }

// [2] 实现模型数据过滤
    QSortFilterProxyModel *cpu_rank_proxy_model = new QSortFilterProxyModel(this);
    cpu_rank_proxy_model->setSourceModel(cpu_rank_model); // 绑定源模型
    cpu_rank_proxy_model->setFilterRole(CpuRankViewModel::CpuRankMingCheng); // 指定过滤角色
    ui->cpu_rank_list->setModel(cpu_rank_proxy_model);

    connect(ui->cpu_filter, &QLineEdit::textChanged, [=](const QString &text){
        // 同步过滤条件到代理模型
        if (text.isEmpty()) {
            cpu_rank_proxy_model->setFilterFixedString(text); // 清空过滤
        } else {
            cpu_rank_proxy_model->setFilterWildcard(text); // 设置通配符过滤（支持模糊匹配）
        }
    });
}

CpuRankMVCMainWindow::~CpuRankMVCMainWindow()
{
    delete ui;
}
